import { _decorator, Component, Node, Collider, ITriggerEvent } from 'cc'
import { Constant } from '../framework/Constant'
import { PoolManager } from '../framework/PoolManager'
const { ccclass, property, menu } = _decorator

/**
 * Predefined variables
 * Name = bullet
 * DateTime = Thu Feb 10 2022 19:47:24 GMT+0800 (中国标准时间)
 * Author = ashscc
 * FileBasename = bullet.ts
 * FileBasenameNoExtension = bullet
 * URL = db://assets/script/bullet/bullet.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/en/
 *
 */
//子弹超出屏幕捕捉的z轴坐标
const OUT_OF_BACKGROUND_RANGE_Z: number = -50

@ccclass('Bullet')
@menu('bullet/Bullet')
export class Bullet extends Component {
  private _bulletSpeed = 0
  private _isEnemyBullet: boolean = false

  private _bulletDirection: number = Constant.BulletType.MIDDLE 

  onEnable() {
    const collider = this.node.getComponent(Collider)
    collider.on('onTriggerEnter', this._onTriggerEnter, this)
  }

  onDisable() {
    const collider = this.node.getComponent(Collider)
    collider.off('onTriggerEnter', this._onTriggerEnter, this)
  }

  update(deltaTime: number) {
    if (this._isEnemyBullet) {
      const pos = this.node.position
      this.node.setPosition(pos.x, pos.y, pos.z + this._bulletSpeed)
      //如果超过摄像机捕捉范围则destroy
      if (this.node.position.z > -OUT_OF_BACKGROUND_RANGE_Z) {
        PoolManager.putNode(this.node)
        // this.node.destroy()
      }
    } else {
      const pos = this.node.position
      if(this._bulletDirection === Constant.BulletType.LEFT){
        this.node.setPosition(pos.x - this._bulletSpeed * 0.2, pos.y, pos.z - this._bulletSpeed)
      }else if(this._bulletDirection === Constant.BulletType.RIGHT){
        this.node.setPosition(pos.x + this._bulletSpeed * 0.2, pos.y, pos.z - this._bulletSpeed)
      }else {
        this.node.setPosition(pos.x, pos.y, pos.z - this._bulletSpeed)
      }
      //如果超过摄像机捕捉范围则destroy
      if (this.node.position.z < OUT_OF_BACKGROUND_RANGE_Z) {
        PoolManager.putNode(this.node)
        // this.node.destroy()
      }
    }
  }

  show(bulletSpeed: number, isEnemyBullet: boolean, bulletDirection: number = Constant.BulletType.MIDDLE) {
    this._bulletSpeed = bulletSpeed
    this._isEnemyBullet = isEnemyBullet
    this._bulletDirection = bulletDirection
  }

  private _onTriggerEnter(event: ITriggerEvent) {
    //子弹只能和玩家飞机或者敌机碰撞，碰撞就消失
    PoolManager.putNode(this.node)
    // this.node.destroy()
  }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.4/manual/en/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.4/manual/en/scripting/decorator.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.4/manual/en/scripting/life-cycle-callbacks.html
 */
